<template>
	<view class="custom-number">
		<view
		class="minus"
		@click="handleMinus" 
		hover-class="custom_hover" 
		:hover-stay-time="200">
			<image src="/static/common/minus_text.png" mode=""></image>
		</view>
		<view class="input_wrap">
			<view class="input">
				<input type="number" :value="modelValue" @input="onInput" :disabled="disabled"/>
			</view>
			<view class="unit" v-if="unit">{{ unit }}</view>
		</view>
		<view 
		class="plus" 
		@click="handlePlus"
		hover-class="custom_hover"
		:hover-stay-time="200">
			<image src="/static/common/plus_text.png" mode=""></image>
		</view>
	</view>
</template>

<script setup>
	import { ref,defineComponent,defineProps } from 'vue';
	import { floatAdd,floatSub } from '../../utils/util.js'

	defineComponent({
		name:'custom-number'
	})
	
	const props = defineProps({
		modelValue: {
			type: Number,
			default: 0
		},
		type: {
			type: String,
			default: 'number'
		},
		disabled:{
			type:Boolean,
			default:false
		},
		step:{
			type: Number,
			default: 1
		},
		unit: {
			type: String,
			default: ''
		},
		max:{
			type: Number,
			default: 99
		}
	})
	
	const emit = defineEmits(['update:modelValue','change'])
	
	const onInput = (event) => {
	  // 如果使用原生 input，可能需要 event.detail.value；u-input 可能直接返回值
	  const value = event.detail?.value ?? event;
	  emit('update:modelValue', Number(value));
	  emit('change', Number(value));
	};
	
	const handlePlus = ()=>{
		if(!props.modelValue){
			emit('update:modelValue',1)
			return
		}
		if(props.modelValue == props.max)return;
		emit('update:modelValue',floatAdd(props.modelValue,props.step))
		emit('change',floatAdd(props.modelValue,props.step))
	}
	const handleMinus = ()=>{
		if(props.modelValue > 0){
			const value = floatSub(props.modelValue,props.step) < 0 ? 0:floatSub(props.modelValue,props.step)
			emit('update:modelValue',value)
			emit('change',value)
		}
	}
</script>

<style lang="scss">
	.custom-number{
		display: flex;
		align-items: center;
		width: max-content;
		border: 1rpx solid #D7D7D7;
		border-radius: 8rpx;
		box-sizing: border-box;
		color:#333333;
		font-size: 24rpx;
		.minus,.plus{
			width: 48rpx;
			height: 48rpx;
			line-height: 48rpx;
			text-align: center;
			display: flex;
			justify-content: center;
			align-items: center;
		}
		.plus image{
			width:16rpx;
			height:17rpx;
		}
		.minus image{
			width: 17rpx;
			height:3rpx;
		}
		.input_wrap{
			display: flex;
			align-items: center;
			width: 88rpx;
			padding: 0 10rpx;
			box-sizing: border-box;
			height: 48rpx;
			line-height: 48rpx;
			border-style:solid;
			border-color:#D7D7D7;
			border-width: 0 1rpx 0 1rpx;
			.input{
				flex: 1;
				input{
					width: 100%;
					text-align: center;
				}
			}
		}
	}
</style>